﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using NetFrame.Net.TCP.Sock.Asynchronous;
using System.Net;

namespace NetServer
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            MyLogger.doInit();
        }
        AsyncSocketTCPServer openServer = null;
        List<AsyncSocketState> Clients = new List<AsyncSocketState>();
        private void butOpen_Click(object sender, EventArgs e)
        {
            IPAddress iptxt = IPAddress.Parse(txtIp.Text.Trim());
            int Porttxt = int.Parse(txtPort.Text.Trim());
            openServer = new AsyncSocketTCPServer(iptxt, Porttxt, 1024);
            try
            {
                openServer.Start();
            }
            catch (Exception error)
            {
                ErrorRecordFile.WriteError(error);
                return;
            }
            openServer.ClientConnected += openServer_ClientConnected;
            openServer.ClientDisconnected += openServer_ClientDisconnected;

            openServer.DataReceived += openServer_DataReceived;

            openServer.PrepareSend += openServer_PrepareSend;
            openServer.CompletedSend += openServer_CompletedSend;

            openServer.NetError += openServer_NetError;
            openServer.OtherException += openServer_OtherException;
            txtIp.Enabled = false;
            txtPort.Enabled = false;
            butOpen.Enabled = false;
            MessageBox.Show("服务开启成功！");
        }

        private void butClose_Click(object sender, EventArgs e)
        {
            openServer.Stop();
            txtIp.Enabled = true;
            txtPort.Enabled = true;
            butOpen.Enabled = true;
        }
        #region 连接
        /// <summary>
        /// 与客户端的连接已建立事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openServer_ClientConnected(object sender, AsyncSocketEventArgs e)
        {
            AsyncSocketState client = e._state;
            string ClientIpAndPort = client.ClientSocket.RemoteEndPoint.ToString();
            Clients.Add(client);
        }
        /// <summary>
        /// 与客户端的连接已断开事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openServer_ClientDisconnected(object sender, AsyncSocketEventArgs e)
        {
            ErrorRecordFile.WriteError("客户端断开连接");
        }
        #endregion
        /// <summary>
        /// 接收的数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openServer_DataReceived(object sender, AsyncSocketEventArgs e)
        {
            try
            {
                string RcvData = System.Text.Encoding.UTF8.GetString(e._state.RecvDataBuffer);
                string IpAndPort = e._state.ClientSocket.RemoteEndPoint.ToString();
                this.Invoke(new Action(() =>
                {
                    txtReceiveMsg.Text += Environment.NewLine + IpAndPort + "：" + RcvData;
                }));
                //接收数据后处理数据并发数据
                byte[] byteArray = SendDatas.SendData(IpAndPort, RcvData);
                this.Invoke(new Action(() =>
                {
                    string msg = System.Text.Encoding.UTF8.GetString(byteArray);
                    txtSendMsg.Text += Environment.NewLine + IpAndPort + "：" + msg + RcvData;
                }));
                openServer.Send(e._state, byteArray);
            }
            catch (Exception error)
            {
                ErrorRecordFile.WriteError(error);
                return;
            }
        }

        private void Send()
        {
            //ClientSocket
            //AsyncSocketState state = new AsyncSocketState();

            //openServer.Send(state, null);
        }
        #region 发送数据时触发
        /// <summary>
        /// 发送数据前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openServer_PrepareSend(object sender, AsyncSocketEventArgs e) { }
        /// <summary>
        /// 数据发送完毕事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openServer_CompletedSend(object sender, AsyncSocketEventArgs e) { }
        #endregion

        #region 异常时触发
        /// <summary>
        /// 网络错误事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openServer_NetError(object sender, AsyncSocketEventArgs e)
        {
            ErrorRecordFile.WriteError("网络错误");
        }
        /// <summary>
        /// 异常事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openServer_OtherException(object sender, AsyncSocketEventArgs e)
        {
            ErrorRecordFile.WriteError("程序异常");
        }
        #endregion

    }
}
